#include "./Looper.h"
#include "./Handler.h"
#include "./Message.h"
#include <thread>
#include <unistd.h>
#include <iostream>

#define LOOP 99999999

using namespace std;

void testFunc(Handler *handle) {
    for (int i = 0; i < LOOP; i++) {
        printf("send msg.\n");
        Message *msg = Message::obtain();
        handle->post([](Message *) {
            cout << "this msg run on thread: " << std::this_thread::get_id() << endl;
        });

        sleep(1);
    }
}

void testFunc2(Handler *handle) {
    for (int i = 0; i < LOOP; i++) {
        cout << "send msg.\n";
        Message *msg = Message::obtain();
        msg->what = 1;
        handle->sendMessage(msg);

        sleep(1);
    }
}

class MyHandler : public Handler {
public:
    MyHandler() : Handler() {
    }

    MyHandler(Looper *looper) : Handler(looper) {
    }

    ~MyHandler() {}

    virtual void handleMessage(Message *msg) {
        cout << "handle msg " << msg->what << " on thread:" << std::this_thread::get_id() << endl;
    }
};

int handler_main() {
    cout << "main thread id is: " << std::this_thread::get_id() << endl;
    Looper *lp = Looper::prepare();
    Handler *handler = new Handler();
    Handler *handler2 = new MyHandler(lp);
    thread t(testFunc, handler);
    thread t2(testFunc2, handler2);
    Looper::loop();
    return 0;
}